<template>
  <div class="app-container" v-loading="loading">
    <el-backtop visibility-height="10"></el-backtop>
    <el-row>
      <el-form :model="conditions" ref="newsForm" size="small" :inline="true" label-width="68px">
        <el-form-item label="新闻标题" prop="title">
          <el-input v-model="conditions.title" placeholder="请输入新闻标题" clearable></el-input>
        </el-form-item>
        <el-form-item label="发布人" prop="issuer">
          <el-input v-model="conditions.issuer" placeholder="请输入发布人" clearable></el-input>
        </el-form-item>
        <el-form-item label="发布时间" prop="issue_time">
          <el-date-picker
            v-model="conditions.issue_time"
            type="daterange"
            format="yyyy-MM-DD" value-format="yyyy-MM-DD"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button
            icon="el-icon-search"
            type="primary"
            @click="query"
            plain
          >
            搜索
          </el-button>
          <el-button
            icon="el-icon-refresh"
            @click="reset"
            plain
          >
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-row>
    <el-row :gutter="10">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" :loading="saveBtnLoading"
                   @click="openArticleDialog"
        >写文章
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single"
                   @click="openEditArticleDialog"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple"
                   @click="handleDeleteArticle"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="info" plain icon="el-icon-message" size="mini" :disabled="single"
                   @click="handleArticleDetails"
        >预览
        </el-button>
      </el-col>
    </el-row>
    <el-row>
      <el-table
        :data="news"
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="50" align="center"/>
        <el-table-column label="编号" type="index" align="center"></el-table-column>
        <el-table-column label="标题" prop="title" align="center"></el-table-column>
        <el-table-column label="副标题" prop="sub_title" align="center"></el-table-column>
        <el-table-column label="封面图" prop="title_picture" align="center">
          <template slot-scope="scope">
            <el-image v-if="scope.row.title_picture" style="width: 100px" :fit="contain"
                      :src="server + scope.row.title_picture"
            ></el-image>
            <el-image v-else style="width: 100px">
              <div slot="error" class="image-slot">
                <i class="el-icon-picture-outline"></i>
              </div>
            </el-image>
          </template>
        </el-table-column>
        <el-table-column label="发布人" prop="issuer" align="center"></el-table-column>
        <el-table-column
          label="发布时间" align="center"
          width="150"
        >
          <template slot-scope="scope">
            <i class="el-icon-time"></i>
            <span style="margin-left: 10px">{{ msToDate(scope.row.issue_time).withoutTime }}</span>
          </template>
        </el-table-column>
        <el-table-column label="阅读次数" prop="read_num" align="center" width="100"></el-table-column>
        <el-table-column label="是否展示" prop="is_deleted" align="center" width="100">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.is_deleted"
              :active-value="0"
              :inactive-value="1"
              @change="handleStatusChange(scope.row)"
            ></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="200">
          <template slot-scope="scope">
            <el-button size="mini" type="text" icon="el-icon-reading"
                       @click="handleArticleDetails(scope.row.id)"
            >详情
            </el-button>
            <el-button size="mini" type="text" icon="el-icon-edit"
                       @click="openEditArticleDialog(scope.row.id)"
            >修改
            </el-button>
            <el-button size="mini" type="text" icon="el-icon-delete"
                       @click="handleDeleteArticle(scope.row.id)"
            >删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-row>
    <el-row type="flex" justify="center" style="margin-top: 20px">
      <el-pagination
        background
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="conditions.currentPage"
        :page-sizes="[10, 25, 50, 100]"
        :page-size="conditions.size"
        layout="total, sizes, prev, pager, next, jumper"
        :total="news_total">
      </el-pagination>
    </el-row>
    <el-dialog
      title="新闻预览"
      :visible.sync="previewDialogVisible"
      width="1000px"
      append-to-body
      :close-on-click-modal="false"
      :before-close="handlePreviewDialogClose"
    >
      <div v-loading="previewDialogLoading">
        <v-md-preview :text="previewContent.content"></v-md-preview>
      </div>
    </el-dialog>
  </div>
</template>

<script>

import { mapGetters } from 'vuex'
import { msToDate } from '@/utils/format'

export default {
  name: 'news',
  data() {
    return {
      loading: false,
      show: true,
      server: window.application.minio_host,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      conditions: {
        title: '',
        issuer: '',
        issue_time: [],
        size: 10,
        currentPage: 1
      },
      content: '',

      saveBtnLoading: false,
      previewDialogVisible: false,
      previewDialogLoading: false,
      previewContent: {
        id: '',
        news_id: '',
        content: ""
      }
    }
  },
  mounted() {
    // this.$nextTick(() => {})
    this.query()
  },
  computed: {
    ...mapGetters(['news','news_total'])
  },
  methods: {
    msToDate,
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    query() {
      this.loading = true
      this.$store.dispatch('news/getNews', this.conditions)
        .then((resp) => {

        })
        .catch((error) => {
          this.$message.error(error)
        })
        .finally(() => {
          setTimeout(() => {
            this.loading = false
          }, 1500)
        })
    },
    reset() {
      this.conditions = {
        title: '',
        issuer: '',
        issue_time: []
      }
      this.query()
    },
    openArticleDialog() {
      this.saveBtnLoading = true
      this.show = !this.show
      this.$store.dispatch('news/createNewsInfo').then((resp) => {
        if (resp.data.code === 1) {
          this.$router.push({ path: 'save-news', query: { id: resp.data.data } })
        } else {
          this.$message.error('系统异常！')
        }
      }).catch((error) => {
        this.$message.error('系统异常！' + error)
      }).finally(() => {
        setTimeout(() => {
          this.saveBtnLoading = false
        })
      })
    },
    openEditArticleDialog(id) {
      if (id instanceof PointerEvent) {
        this.$router.push({ path: 'save-news', query: { id: this.ids[0] } })
      } else {
        this.$router.push({ path: 'save-news', query: { id: id } })
      }
    },
    handleDeleteArticle(arg) {
      if (arg instanceof PointerEvent) {
        this.$confirm('此操作将永久删除这些新闻，是否继续', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消'
        }).then(() => {
          // 确定事件
          this.$store.dispatch('news/removeNewsById', { 'ids': this.ids })
            .then(resp => {
              if (resp) {
                this.$message.success('新闻删除成功! ')
              } else {
                this.$message.error('新闻删除失败，请联系管理员')
              }
            })
            .catch(error => this.$message.error(error))
            .finally(() => this.query())
        }).catch(() => {
        })
      } else {
        this.$confirm(`将删除编号为 ${arg} 的新闻 ，是否继续`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消'
        }).then(() => {
          // 确定事件
          this.$store.dispatch('news/removeNewsById', { 'ids': [arg] })
            .then(resp => {
              if (resp) {
                this.$message.success('新闻删除成功! ')
              } else {
                this.$message.error('新闻删除失败，请联系管理员')
              }
            })
            .catch(error => this.$message.error(error))
            .finally(() => this.query())
        }).catch(() => {
        })
      }
    },
    handleArticleDetails(id) {
      if (id instanceof PointerEvent) {
        this.getArticleContent(this.ids[0])
      } else {
        this.getArticleContent(id)
      }
    },
    getArticleContent(id) {
      this.previewDialogVisible = true
      this.previewDialogLoading = true
      this.$store.dispatch('news/getPreviewNewsContent', id)
        .then((resp) => {
          this.previewContent = resp.data.data
          setTimeout(() => {
            this.previewDialogLoading = false
          }, 1500)
        }).catch((error) => {
        this.$message.error(error)
      })
    },
    handlePreviewDialogClose() {
      this.previewContent = {
        id: '',
        news_id: '',
        content: ''
      }
      this.previewDialogVisible = false
      this.previewDialogLoading = false
    },
    handleStatusChange(row) {
      let text = row.is_deleted === 0 ? '启用' : '停用'
      this.$confirm(`确认要 ${text} 该新闻吗?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$store.dispatch('news/changeState', row)
          .then((resp) => {
            if (resp.data) this.$message({ type: 'success', message: `成功 ${text} 该新闻` })
            this.query()
          })
      }).catch(() => {
        row.is_deleted = row.is_deleted === 0 ? 1 : 0
      })
    },
    handleSizeChange(val) {
      this.conditions.size = val
      this.query()
    },
    handleCurrentChange(val) {
      this.conditions.currentPage = val
      this.query()
    },
  }
}

</script>

<style scoped lang="scss">

</style>
